<?php
/**
 * 后台代理 store 的查看所有微信用户
 *
 * Author: lyun
 * Date: 2018/3/30
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\Admin\Store;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\Store\WechatUserIndexRequest;
use App\Http\Requests\Wechat\SkinRecordIndexRequest;
use App\Models\Admin\StoreAdmin;
use App\Models\Customer\Customer;
use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\SkinDetector;
use App\Models\Store\HmSkinRecord;
use App\Models\Store\SkinRecord;
use App\Models\Store\Store;
use App\Models\Store\WaxSkinRecord;
use App\Services\ExcelExporters\UserExporter;
use App\Services\OpenWechat\WechatUserRepository;
use App\Services\Presenters\HmSkinData;
use App\Services\Repositories\SkinRecord\SkinRecordRepository;
use App\Services\Utils\Emoji;
use App\Services\Utils\Guard;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;


class WechatUserController extends ApiController
{
    const ROUTES = [
        'index'                  => 'api.admin.store.wechat-user.index',
        'showWithSkinRecordInfo' => 'api.admin.store.wechat-user.show-with-skin-record-info',
    ];

    protected $wechatUserRepository;
    protected $skinRecordRepository;

    public function __construct(WechatUserRepository $wechatUserRepository,
                                SkinRecordRepository $skinRecordRepository)
    {
        $this->skinRecordRepository = $skinRecordRepository;
        $this->wechatUserRepository = $wechatUserRepository;
    }


    /**
     * 后台店铺,肤质检测数据管理,筛选微信用户
     * @test
     *
     * @param WechatUserIndexRequest $request
     * @param WechatUserRepository $wechatUserRepo
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(WechatUserIndexRequest $request,
                          WechatUserRepository $wechatUserRepo)
    {
        // 超管才能操作的
        $this->checkIsTrue(StoreAdmin::checkIsSuperMan(), trans('admin.is_super_man'));

        $store = Guard::storeAdmin()->store;
        $customer = $store->customer;

        /** @var LengthAwarePaginator $wechat_users */
        $wechat_users = $wechatUserRepo
            ->adminSkinRecordIndexQuery($request, [$store->id])
            ->paginate($request->per_page ?: 15);

        /** @var Collection $user_collection */
//        $user_collection = $wechat_users->getCollection();
//        $this->transformWechatUsers($user_collection);

        $appid = isset($customer->authorizer->authorizer_appid)
            ? ($customer->authorizer->authorizer_appid)
            : null;

        return $this->response(compact('wechat_users', 'appid'));
    }

    /**
     * 店铺后台，肤质检测数据管理,测肤微信用户信息和肤质检测统计数据
     * @test
     *
     * @param SkinRecordIndexRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function showWithSkinRecordInfo(SkinRecordIndexRequest $request)
    {
        $customer_id = Guard::store()->customer_id;

        $wechat_user = WechatUser::findByOpenId($request->openid);
            $this->checkItemExist($wechat_user,trans('app.wechat_user_error'));

        // 微信用户数据
        $this->wechatUserRepository->appendPersonalCardInfo($wechat_user);
        $this->wechatUserRepository->appendStoresSkinRecordCountInfo($wechat_user, [Guard::store()->id]);

        $skin_detector_id = (int) $request->skin_detector_id;
        $skin_record_ids = $this->skinRecordRepository
            ->searchByWechatAndSkinDetector($wechat_user, $skin_detector_id)
            ->modelKeys();

        // 测肤趋势图数据
        $skin_records = $this->skinRecordRepository->getSkinRecords($skin_detector_id, $skin_record_ids, $customer_id);

        $wechat_user_info = $wechat_user;

        return $this->response(compact('wechat_user_info','skin_records'));
    }

    /**
     * 后台店铺,肤质检测数据管理,导出微信用户的数据
     *
     * @param Request $request
     * @throws \Exception
     * @throws \Maatwebsite\Excel\Exceptions\LaravelExcelException
     */
    public function exportStoreUser(Request $request)
    {
        // 超管才能操作的
        $this->checkIsTrue(StoreAdmin::checkIsSuperMan(), trans('admin.is_super_man'));

        $store = Guard::storeAdmin()->store;

        if ($request->age_range) {
            $time_range = WechatUserRepository::ageToTimeRange($request->age_range);
        } else {
            $time_range = null;
        }

        $wechat_users = $store->wechatUsers()
            ->filterTimeRange($time_range, 'born_at')
            ->filterSex($request->sex)
            ->columnsKeywordOrLike(['nickname', 'phone', 'name', 'nickname_unicode'], $request->keywords)
            ->get();

        (new UserExporter)->export($wechat_users, trans('admin.store_user'));

    }

    /**
     * @param $id
     * @return array|\Illuminate\Http\Response
     */
    public function show($id)
    {
        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::find($id);

        return $this->response(compact('wechat_user'));
    }
}
